from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect, reverse
from app1.models import Dept
from app1.util.pagination import Pagination
from openpyxl import load_workbook
from django.conf import settings
import os


def dept_list(request):
    query_params = {}
    q = request.GET.get('q')
    if q:
        query_params['dname__contains'] = q

    queryset = Dept.objects.filter(**query_params)
    page = Pagination(request, queryset)
    return render(request, 'dept/dept_list.html',
                  {'dept_list': page.get_page_result(), 'page_str': page.get_page_str()})


def dept_add(request):
    if request.method == 'GET':
        return render(request, 'dept/dept_add.html')
    dname = request.POST.get('dname')
    loc = request.POST.get('loc')
    Dept.objects.create(dname=dname, loc=loc)
    return redirect(reverse('dept_list'))


def dept_batchadd(request):
    context = {}  # 用于传递消息的上下文

    if request.method == 'POST':
        # 获取上传的Excel文件
        excel_file = request.FILES.get('excel_file')

        # 检查文件是否存在
        if not excel_file:
            context['error_message'] = "请选择要上传的Excel文件"
            return render(request, 'dept/dept_batchadd.html', context)

        # 检查文件扩展名
        if not excel_file.name.endswith('.xlsx'):
            context['error_message'] = "仅支持.xlsx格式的Excel文件"
            return render(request, 'dept/dept_batchadd.html', context)

        try:
            # 使用 openpyxl 处理Excel文件
            wb = load_workbook(excel_file)
            sheet = wb.active

            # 计数器
            success_count = 0
            error_rows = []

            # 遍历行并创建部门对象
            for row_idx, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
                if not row[0] or not row[1]:  # 检查是否为空行
                    continue

                try:
                    dept_name, location = row[0], row[1]
                    # 使用正确的字段名称：dname 和 loc
                    Dept.objects.create(dname=dept_name, loc=location)
                    success_count += 1
                except Exception as e:
                    error_rows.append(f"第 {row_idx} 行: {str(e)}")

            # 返回结果信息
            if error_rows:
                context['warning_message'] = (
                        f"成功导入 {success_count} 条记录<br>以下行导入失败:<br>" +
                        "<br>".join(error_rows)
                )
            else:
                context['success_message'] = f"成功导入 {success_count} 条部门记录"
                return HttpResponseRedirect(reverse('dept_list'))

        except Exception as e:
            # 处理可能的异常
            context['error_message'] = f"处理Excel文件时出错: {str(e)}"

    # 如果是GET请求或处理中有错误，显示上传表单
    return render(request, 'dept/dept_batchadd.html', context)
def download_dept_template(request):
    # 模板文件路径
    template_path = os.path.join(settings.BASE_DIR, 'app1', 'templates', 'dept', 'dept_template.xlsx')

    if os.path.exists(template_path):
        with open(template_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            response['Content-Disposition'] = 'attachment; filename="部门模板.xlsx"'
            return response
    return HttpResponse("模板文件不存在", status=404)

def dept_update(request):
    if request.method == 'GET':
        deptno = request.GET.get('deptno')
        dept = Dept.objects.filter(deptno=deptno).first()
        return render(request, 'dept/dept_update.html', {'dept': dept})
    deptno = request.POST.get('deptno')
    dname = request.POST.get('dname')
    loc = request.POST.get('loc')
    Dept.objects.filter(deptno=deptno).update(dname=dname, loc=loc)
    return redirect(reverse('dept_list'))


def dept_delete(request):
    deptno = request.GET.get('deptno')
    Dept.objects.filter(deptno=deptno).delete()
    return redirect(reverse('dept_list'))